import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  Logger,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { ResponseUtil } from '../utils/response.util';
import { ThrottlerException } from '@nestjs/throttler';
import { ResponseMsgKey } from '../constants/api-response.constant';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionFilter.name);
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    this.logger.error(exception.stack);
    this.logger.error(JSON.stringify(exception));
    response.json(
      ResponseUtil.fail(
        exception instanceof HttpException
          ? exception.getStatus()
          : HttpStatus.BAD_REQUEST,
        this.getErrorMsg(exception),
      ),
    );
  }

  private getErrorMsg(exception: any): string {
    if (exception instanceof ThrottlerException) {
      return ResponseUtil.translate(ResponseMsgKey.TOO_MANY_REQUESTS);
    } else if (exception instanceof HttpException) {
      const response = exception.getResponse();
      if (typeof response === 'string') {
        return ResponseUtil.translate(response);
      } else if (response['message']) {
        return ResponseUtil.translate(response['message']);
      } else {
        return JSON.stringify(response);
      }
    } else {
      return ResponseUtil.translate(exception?.message);
    }
  }
}
